package tv.scolopender.asynctask;

import java.util.ArrayList;

import tv.scolopender.json.NewsJSON;
import tv.scolopender.model.News;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;

public class NewsAsyncTask extends AsyncTask<Void, Void, ArrayList<News>> {
	private final Activity activity;

	public NewsAsyncTask(Activity activity) {
		super();
		this.activity = activity;
	}

	@Override
	protected ArrayList<News> doInBackground(Void... params) {
		// lokal gespeicherte id der letzten news auslesen
		SharedPreferences settings = activity.getSharedPreferences(
				"ScoloPrefs", Context.MODE_PRIVATE);
		int lastNewsId = settings.getInt("lastNewsId", 0);

		if (lastNewsId == 0) {
			// wenn noch keine news gelesen wurden, d. h. erster start
			lastNewsId = NewsJSON.selectLatestNewsId() - 1;
		}
		ArrayList<News> news = NewsJSON.selectNews(lastNewsId);
		if (news.size() > 0) {
			// lokal speichern
			// settings = getSharedPreferences("ScoloPrefs",
			// Context.MODE_PRIVATE);
			SharedPreferences.Editor editor = settings.edit();
			editor.putInt("lastNewsId", news.get(news.size() - 1).getId());
			editor.commit();
		}
		return news;
	}
}